package com.tq.core;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.*;

/**
 * @author TqCoder
 * @since 2.0.0
 */
public class AbstractAlgorithm {


    public static void main(String[] args) {
        treeSortDemo();
    }

    // ------------------------------------------- 场景 ----------------------------------------------------------------

    // 树排序
    // List<Org> orgs;
    // 有层级的树结构

    @Data
    @AllArgsConstructor
    static class Org {
        private Long id;
        private Long parentId;
        private String name;

        //------- calc field ---------
        private List<Org> children;

        public Org(Long id, Long parentId, String name){
            this.id = id;
            this.parentId = parentId;
            this.name = name;
        }
    }


    private static void treeSortDemo() {
        List<Org> orgs = initData();
        List<Org> sortedTree = sortTree(orgs);
        sortedTree.forEach(org -> System.out.println(org.getId() + " " + org.getName()));
    }

    private static List<Org> sortTree(List<Org> orgs) {
        Org rootOrg = orgs.stream().filter(org -> org.getParentId() == 0L).findFirst().orElseThrow(() -> new IllegalArgumentException("没有根节点"));
        Queue<Org> queue = new LinkedList<>();
        queue.add(rootOrg);

        List<Org> sortedOrgs = new ArrayList<>();
        while (!queue.isEmpty()) {
            Org parentOrg = queue.poll();
            sortedOrgs.add(parentOrg);
            List<Org> children = orgs.stream().filter(org -> parentOrg.getId().equals(org.getParentId())).toList();
            queue.addAll(children);
            parentOrg.setChildren(children);
        }

        return sortedOrgs;
    }

    private static List<Org> initData() {
        return List.of(
                new Org(1L, 0L, "1"),
                new Org(3L, 1L, "3"),
                new Org(4L, 2L, "4"),
                new Org(5L, 2L, "5"),
                new Org(6L, 3L, "6"),
                new Org(7L, 3L, "7"),
                new Org(2L, 1L, "2")
        );
    }

    // -------------------------------------------Question -------------------------------------------------------------
    // 引用传递 值传递 List list = new ArrayList<>(); 这个是值传递还是引用传递为什么
    // 值传递





}
